<template>
  <div>
    <el-row>
      <el-col>
        <el-select
          v-model="value"
          filterable
          remote
          reserve-keyword
          placeholder="请输入商品类别名称"
          :remote-method="remoteMethod"
          :loading="loading"
        >
          <el-option
            v-for="item in options"
            :key="item[0]"
            :label="item[0]"
            :value="item[0]"
          />
        </el-select>
      </el-col>
    </el-row>
    <el-row style="margin-top: 20px">
      <el-col>
        <el-table
          :data="tableData"
          height="300"
          border
          style="width: 100%"
        >
          <el-table-column
            type="index"
            :index="indexMethod"
          />
          <el-table-column
            prop="name"
            label="商品"
          />
          <el-table-column
            prop="pv"
            label="浏览量"
          />
          <el-table-column
            prop="fav"
            label="收藏量"
          />
          <el-table-column
            prop="cart"
            label="加购量"
          />
          <el-table-column
            prop="buy"
            label="购买量"
          />
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'SelectorSearch',
  data() {
    return {
      tableData: [],
      options: [],
      value: '',
      list: [],
      loading: false
    }
  },
  watch: {
    value: {
      handler(newItem, oldItem) {
        console.log('new: ' + newItem)
        console.log(typeof newItem)
        console.log(newItem.name)
        if (typeof (newItem) === 'string') {
          console.log('string fun')
          this.queryItemInfo(newItem)
        } else {
          console.log('obj func')
          this.queryItemInfo(newItem.name)
        }
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.getOneType()
    })
  },
  methods: {
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          axios.get('http://127.0.0.1:8000/all/query_type?param=' + query).then(response => {
            this.options = response.data.types
          }).catch(err => {
            console.log(err)
          })
        }, 200)
      } else {
        this.options = []
      }
    },
    getOneType() {
      axios.get('http://127.0.0.1:8000/all/get_one_type').then(response => {
        this.value = response.data.type[0]
      })
    },
    queryItemInfo(id) {
      axios.get('http://127.0.0.1:8000/all/query_item_info?param=' + id).then(response => {
        this.tableData = response.data.data
      }).catch(err => {
        console.log(err)
      })
    },
    indexMethod(index) {
      return index
    }
  }
}
</script>
